package com.flight.trans.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.flight.trans.R;
import com.flight.trans.adapter.EnterPortTakeDetailsAdapter;
import com.flight.trans.bean.ChannelBean.ChannelData;
import com.flight.trans.bean.EnterPortStorageBean;
import com.flight.trans.bean.EnterPortTakeSaveBean;
import com.flight.trans.bean.FileBean;
import com.flight.trans.global.Constant;
import com.flight.trans.global.ConstantInfo;
import com.flight.trans.http.GlideLoader;
import com.flight.trans.http.NetworkUtils;
import com.flight.trans.http.network.OkGoBackListener;
import com.flight.trans.listener.OnItemClickListener;
import com.flight.trans.listener.OnTextClickListener;
import com.flight.trans.util.CommonUtils;
import com.flight.trans.util.JsonUtils;
import com.flight.trans.view.dialog.AlertDialog;
import com.flight.trans.view.dialog.ChanelDialog;
import com.flight.trans.view.dialog.SignAlertDialog;
import com.flight.trans.base.BaseActivity;
import com.flight.trans.bean.EnterPortTakeBean.EnterPortTakeData;
import com.flight.trans.bean.EnterPortTakeDetailBean.EnterPortTakeDetailData;
import com.flight.trans.util.ToastUtils;
import com.flight.trans.view.dialog.StorageContainerDialog;
import com.lzy.okgo.model.HttpParams;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提货详情
 */
public class EnterPortTakeDetailsActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout mLlContainer ;
    private TextView mTvTitleName;
    private RecyclerView mRvContainer ;

    private Button mBtnApplicationReceipt ,//事故签字
            mBtnSignedTakeGoods ;//签字提货

    private TextView mTvTakeNo ,//提货单号
            mTvCreatePerson ,//开单人
            mTvReceivingPerson ,//收货人
            mTvTakePersonnel ,//提货人
            mTvTakePersonnelID ,//提货人证件号
            mTvTakeRoute ;//提货通道

    private ImageView mIvSeeTakePersonPhoto ;//查看提货人照片
    private ImageView mIvSelected ;// 全部选择

    private EnterPortTakeData mTakeData ;
    private EnterPortTakeDetailsAdapter mTakeDetailsAdapter;
    private List<EnterPortTakeDetailData> mTakeDetailDataList ;

    private FileBean mUploadFileData ;

    @Override
    protected int setContentView() {
        return R.layout.activity_enter_port_take_details;
    }

    @Override
    protected void initView() {
        mLlContainer = findViewById(R.id.mLlContainer);
        mTvTitleName = findViewById(R.id.mTvTitleName);
        mRvContainer = findViewById(R.id.mRvContainer);

        mBtnApplicationReceipt = findViewById(R.id.mBtnApplicationReceipt);
        mBtnSignedTakeGoods = findViewById(R.id.mBtnSignedTakeGoods);

        mIvSelected = findViewById(R.id.mIvSelected);
        mIvSeeTakePersonPhoto = findViewById(R.id.mIvSeeTakePersonPhoto);

        mTvTakeNo = findViewById(R.id.mTvTakeNo);
        mTvCreatePerson = findViewById(R.id.mTvCreatePerson);
        mTvReceivingPerson = findViewById(R.id.mTvReceivingPerson);
        mTvTakePersonnel = findViewById(R.id.mTvTakePersonnel);
        mTvTakePersonnelID = findViewById(R.id.mTvTakePersonnelID);
        mTvTakeRoute = findViewById(R.id.mTvTakeRoute);
    }

    @Override
    protected void initData() {
        mTakeData = (EnterPortTakeData) mBundle.getSerializable(Constant.INFO);
        IsEditor = mBundle.getInt(Constant.IsEditor) != 2;

        ConstantInfo.UnusualIDList.clear();

        mTvTakeNo.setText(!TextUtils.isEmpty(mTakeData.getConsigneeNo()) ? mTakeData.getConsigneeNo() : getString(R.string.text_not));
        mTvCreatePerson.setText(!TextUtils.isEmpty(mTakeData.getConsigneeCreateByName()) ? mTakeData.getConsigneeCreateByName() : getString(R.string.text_not));
        mTvReceivingPerson.setText(!TextUtils.isEmpty(mTakeData.getReceiverName()) ? mTakeData.getReceiverName() : getString(R.string.text_not));
        mTvTakePersonnel.setText(!TextUtils.isEmpty(mTakeData.getConsigneeName()) ? mTakeData.getConsigneeName() : getString(R.string.text_not));
        mTvTakePersonnelID.setText(!TextUtils.isEmpty(mTakeData.getConsigneeIdNum()) ? mTakeData.getConsigneeIdNum() : getString(R.string.text_not));
        mTvTakeRoute.setText(mTakeData.getDeliveryChannel());
        GlideLoader.loader(mTakeData.getConsigneePhoto() , mIvSeeTakePersonPhoto , R.mipmap.icon_see_image);

        mTvTitleName.setText(getString(R.string.title_enter_port_take_goods_details));
        CommonUtils.onFinishTouch(mActivity , mLlContainer);
    }

    @Override
    protected void initConnect() {
        linked(true);
    }


    private void linked(boolean isFirst){
        valueParams = new HttpParams();
        valueParams.put(Constant.Consignee_No , mTakeData.getConsigneeNo());

        NetworkUtils.getEnterPortTakeDetails(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {

                if(isFirst) {
                    mTakeDetailDataList = (List<EnterPortTakeDetailData>) body;

                    if(mTakeDetailDataList == null)
                        mTakeDetailDataList = new ArrayList<>();

                    for (int i = 0; i < mTakeDetailDataList.size(); i++)
                        mTakeDetailDataList.get(i).setSelected(mTakeDetailDataList.get(i).getState() != Constant.Be_Take);
                }else {
                    List<EnterPortTakeDetailData> mDataList = (List<EnterPortTakeDetailData>) body;
                    Map<String , EnterPortTakeDetailData> mDataMap = new HashMap<>();

                    for (int i = 0; i < mDataList.size(); i++) {
                        mDataMap.put(mDataList.get(i).getOrderNo() , mDataList.get(i));
                    }

                    for (int i = 0; i < mTakeDetailDataList.size(); i++) {
                        mTakeDetailDataList.get(i).setInwardStorageDetailData(mDataMap.get(mTakeDetailDataList.get(i).getOrderNo()).getInwardStorageDetailData());
                        mTakeDetailDataList.get(i).setAnomalyCnt(mDataMap.get(mTakeDetailDataList.get(i).getOrderNo()).getAnomalyCnt());
                    }
                }

                initAdapter();
                initLocationButton();
                // 初始化选择
                initSelected(getSelected());
            }
        }, valueParams);
    }

    private void initAdapter(){
        if(mTakeDetailsAdapter == null) {
            mTakeDetailsAdapter = new EnterPortTakeDetailsAdapter(mActivity, mTakeDetailDataList);
            mRvContainer.setAdapter(mTakeDetailsAdapter);
            mRvContainer.setLayoutManager(new LinearLayoutManager(mActivity));

            mTakeDetailsAdapter.setOnItemClickListener(new TakeItemClickListener());
            mTakeDetailsAdapter.setOnTextClickListener(new TakeItemTextClickTextListener());
        }else {
            mTakeDetailsAdapter.updateAdapter(mTakeDetailDataList);
        }
    }

    private void initLocationButton(){
        mBtnApplicationReceipt.setVisibility(IsEditor ? View.VISIBLE : View.GONE);
        mBtnSignedTakeGoods.setVisibility(IsEditor ? View.VISIBLE : View.GONE);

        if(IsEditor) {
            mIvSelected.setOnClickListener(this);
            mTvTakeRoute.setOnClickListener(this);
        }
    }

    /**
     * 条目字段点击事件
     */
    private class TakeItemTextClickTextListener implements OnTextClickListener {
        @Override
        public void onClick(View view, int position) {
            switch (view.getId()){
                case R.id.mTvStorageArea:
                    // 存放区域
                    StorageContainerDialog.getInstance(mActivity)
                            .setContent(mTakeDetailDataList.get(position).getInwardStorageDetailData() , IsEditor)
                            .setConfirmButton(new StorageContainerDialog.OnConfirmClickListener() {
                                @Override
                                public void onClick(List<EnterPortStorageBean> contentList) {
                                    mTakeDetailDataList.get(position).setInwardStorageDetailData(contentList);
                                }
                            })
                            .show();
                    break;
                case R.id.mTvUnusualStatus:
                    // 异常信息
                    mIntent = new Intent(mActivity , UnusualListActivity.class);
                    mBundle = new Bundle();
                    mBundle.putBoolean(Constant.IsEditor , IsEditor);
                    mBundle.putInt(Constant.Business_ID , mTakeDetailDataList.get(position).getInwardOrderId());
                    mBundle.putString(Constant.Key_Order_No , mTakeDetailDataList.get(position).getOrderNo());
                    mBundle.putInt(Constant.Source_Type , 2);
                    mIntent.putExtras(mBundle);
                    turnActForResult(mIntent);
                    break;
                case R.id.mTvOrderNo:
                    // 单号
                    ToastUtils.showToast(mTakeDetailDataList.get(position).getOrderCreateTime());
                    break;
            }
        }
    }

    /**
     * 条目点击事件
     */
    private class TakeItemClickListener extends OnItemClickListener {
        @Override
        public void onClick(View view, int position) {
            mTakeDetailDataList.get(position).setSelected(!mTakeDetailDataList.get(position).isSelected());

            initAdapter();

            // 初始化选择
            initSelected(getSelected());
        }
    }

    @Override
    public void onClick(View v) {
        if(CommonUtils.isFastDoubleClick())
            return;

        switch (v.getId()){
            case R.id.mIbBack:
                onBackPressed();
                break;
            case R.id.mIvSelected:
                // 全选
                if(!IsEditor)
                    return;

                if(mTakeDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                boolean selected = getSelected();
                for (int i = 0; i < mTakeDetailDataList.size(); i++) {
                    mTakeDetailDataList.get(i).setSelected(!selected);
                }
                initAdapter();
                initSelected(!selected);
                break;
            case R.id.mTvTakeRoute:
                // 切换通道
                if(mTakeDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                ChanelDialog.getInstance(mActivity)
                        .getChannelData(Constant.EnterPortTake)
                        .setOnItemClickListener(new ChanelDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(ChannelData channelData) {
                                showConfirmDialog(channelData);
                            }
                        }).show();
                break;
            case R.id.mBtnSignedTakeGoods:
                // 签字提货
                if(mTakeDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                showConfirmSignedTakeGoodsDialog();
                break;
            case R.id.mBtnApplicationReceipt:
                // 申请事故签证
                if(mTakeDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }

                showConfirmApplicationReceiptDialog();
                break;
            case R.id.mIvSeeTakePersonPhoto:
                // 查看提货人照片
                if(mTakeDetailDataList == null){
                    ToastUtils.showToast(R.string.toast_storeroom_inventory_data_null);
                    return;
                }
                
                ArrayList<String> imageList = new ArrayList<>();
                imageList.add("");

                mIntent = new Intent(mActivity , SeePicActivity.class);
                mBundle = new Bundle();
                mBundle.putStringArrayList(Constant.INFO , imageList);
                mBundle.putInt(Constant.POSITION , 0);
                mIntent.putExtras(mBundle);
                turnActForResult(mIntent);
                break;

        }
    }

    /**
     * 修改提货通道
     */
    private void showConfirmDialog(ChannelData channelData) {
        AlertDialog.getInstance(mActivity)
                .setContent(R.string.dialog_reset_channel)
                .setConfirmButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        valueParams = new HttpParams();
                        valueParams.put(Constant.Consignee_No , mTakeData.getConsigneeNo());
                        valueParams.put(Constant.Delivery_Channel , channelData.getCode());

                        NetworkUtils.saveEnterPortChannel(new OkGoBackListener(mActivity) {
                            @Override
                            public void onSuccess(Object body) {
                                ToastUtils.showToast(R.string.toast_reset_success);

                                mTakeData.setDeliveryChannel(channelData.getCode());
                                mTvTakeRoute.setText(channelData.getCode());
                            }
                        }, valueParams);
                    }
                }).show();
    }

    /**
     * 全选、全取消
     * @param isSelected
     */
    private void initSelected(boolean isSelected){
        mIvSelected.setImageDrawable(mActivity.getDrawable(isSelected ? R.mipmap.check_item_sel :R.mipmap.check_item_blue));
    }

    /**
     * 点击提货确认
     */
    private void showConfirmSignedTakeGoodsDialog(){
        String content = getString(R.string.toast_now_select) + getSelectedItems().size() +
                getString(R.string.toast_now_not_select) + (getNotTakeItem().size() - getSelectedItems().size()) +
                getString(R.string.toast_confirm_take);

            if (getSelectedItems().size() != 0) {
                showConfirmDialog(0 , content);
            }else{
                ToastUtils.showToast(R.string.toast_please_select_order);
            }
    }

    /**
     * 点击事故签证
     */
    private void showConfirmApplicationReceiptDialog(){
        if (getSelectItem().size() != 0) {
            if(getSelectItem().size() == 1) {
                showConfirmDialog(1, "是否确认给运单" + getSelectItem().get(0).getOrderNo() + "申请事故签证？");
            }else {
                ToastUtils.showToast(R.string.toast_select_order_one);
            }
        }else{
            ToastUtils.showToast(R.string.toast_please_select_order);
        }
    }

    private void showConfirmDialog(int type , String content){
        AlertDialog.getInstance(mActivity)
                .setContent(content)
                .setConfirmButton(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(type == 0) {
                            showTakeDialog();
                        }else {
                            mIntent = new Intent(mActivity , ApplicationReceiptActivity.class);
                            mBundle = new Bundle();
                            mBundle.putInt(Constant.ID , mTakeDetailDataList.get(getSelectedItem()).getInwardOrderId());
                            mBundle.putInt(Constant.POSITION , getSelectedItem());
                            mBundle.putInt(Constant.DamageLossID , mTakeDetailDataList.get(getSelectedItem()).getDamageLossId());
                            mIntent.putExtras(mBundle);
                            turnActForResult(mIntent);
                        }
                    }
                }).show();
    }

    /**
     * 确认提货
     */
    private void showTakeDialog(){
        if(IsSaveIng){
            ToastUtils.showToast(R.string.toast_save_ing);
            return;
        }

        clickSubmit(0);
    }

    /**
     * 确认提货
     */
    private void showSingleDialog(){
        if(IsSaveIng){
            ToastUtils.showToast(R.string.toast_save_ing);
            return;
        }

        SignAlertDialog.getInstance(mActivity)
                .setConfirmButton(new SignAlertDialog.OnConfirmClickListener() {
                    @Override
                    public void getFile(File signFile) {
                        NetworkUtils.uploadFile(new OkGoBackListener(mActivity) {
                            @Override
                            public void onSuccess(Object body) {
                                mUploadFileData = (FileBean) body;

                                clickSubmit(mUploadFileData.getFileId());
                            }
                        }, signFile);
                    }
                }).show();
    }

    /**
     * 提交
     * @param fileID
     */
    private void clickSubmit(int fileID){
        EnterPortTakeSaveBean takeSaveBean = new EnterPortTakeSaveBean(fileID , getSelectedItems());

        IsSaveIng = true;
        NetworkUtils.saveEnterPortTakeDetails(new OkGoBackListener(mActivity) {
            @Override
            public void onSuccess(Object body) {
                IsSaveIng = false;
                ToastUtils.showToast(R.string.toast_submit_success);
                onFinish(Constant.RESULT_CODE);
            }

            @Override
            public void onError() {
                IsSaveIng = false;
            }
        }, JsonUtils.parseBeanToJson(takeSaveBean));
    }

    /**
     * 获取选择的运单
     * @return
     */
    private List<Integer> getSelectedItems(){
        List<Integer> integerList = new ArrayList<>();
        for (int i = 0; i < mTakeDetailDataList.size(); i++) {
            if(mTakeDetailDataList.get(i).isSelected()
                    && mTakeDetailDataList.get(i).getState() == Constant.Be_Take){
                integerList.add(mTakeDetailDataList.get(i).getInwardOrderDetailId());
            }
        }
        return integerList;
    }

    /**
     * 获取选择的运单
     * @return
     */
    private List<EnterPortTakeDetailData> getSelectItem(){
        List<EnterPortTakeDetailData> integerList = new ArrayList<>();
        for (int i = 0; i < mTakeDetailDataList.size(); i++) {
            if(mTakeDetailDataList.get(i).isSelected()
                    && mTakeDetailDataList.get(i).getState() == Constant.Be_Take){
                integerList.add(mTakeDetailDataList.get(i));
            }
        }
        return integerList;
    }

    /**
     * 获取选择的运单
     * @return
     */
    private int getSelectedItem(){
        int position = -1 ;
        for (int i = 0; i < mTakeDetailDataList.size(); i++) {
            if(mTakeDetailDataList.get(i).isSelected()
                    && mTakeDetailDataList.get(i).getState() == Constant.Be_Take){
                position = i ;
            }
        }
        return position;
    }

    /**
     * 判断是否全部选中
     * @return
     */
    private boolean getSelected(){
        boolean isSelected = true ;
        for (int i = 0; i < mTakeDetailDataList.size(); i++) {
            if(!mTakeDetailDataList.get(i).isSelected()){
                isSelected = false ;
                break;
            }
        }
        return isSelected;
    }

    /**
     * 获取选择的运单
     * @return
     */
    private List<Integer> getNotTakeItem(){
        List<Integer> integerList = new ArrayList<>();
        for (int i = 0; i < mTakeDetailDataList.size(); i++) {
            if(mTakeDetailDataList.get(i).getState() == Constant.Be_Take){
                integerList.add(mTakeDetailDataList.get(i).getInwardOrderDetailId());
            }
        }
        return integerList;
    }

    @Override
    protected void initRefresh(int count) {
        super.initRefresh(count);

        NetworkUtils.checkPageLock(new OkGoBackListener(mActivity) , ConstantInfo.IN_STORAGE_OUT , mTakeData.getConsigneeNo());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        if(requestCode == Constant.REQUEST_CODE && resultCode == Constant.RESULT_CODE){
            mBundle = data.getExtras();

            mTakeDetailDataList.get(mBundle.getInt(Constant.POSITION)).setDamageLossId(mBundle.getInt(Constant.DamageLossID));
            initAdapter();
        } else if(requestCode == Constant.REQUEST_CODE && resultCode == Constant.RESULT_REFRESH_CODE){
            linked(false);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
